use serde::Deserialize;

/// redis连接配置
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct RedisConfig {
    /// 如果指定了url
    /// 则忽略 ssl、host、port、username、password、database的值
    url: Option<String>,
    /// 是否加密
    #[serde(default)]
    ssl: bool,
    /// ip
    host: Option<String>,
    /// 端口
    port: Option<u16>,
    /// 用户名
    username: Option<String>,
    /// 密码
    password: Option<String>,
    /// 库
    database: Option<u16>,
    /// 最大连接
    max_size: Option<u32>,
    /// 最小空闲连接计数
    min_idle: Option<u32>,
    /// 连接超时时间
    connect_timeout: Option<u16>,
    /// 连接最大空闲时间
    idle_timeout: Option<u16>,
}


impl Default for RedisConfig {
    fn default() -> Self {
        Self {
            url: None,
            ssl: false,
            host: None,
            port: None,
            username: None,
            password: None,
            database: None,
            max_size: None,
            min_idle: None,
            connect_timeout: None,
            idle_timeout: None,
        }
    }
}


impl RedisConfig {
    pub fn url(&self) -> Option<&String> {
        self.url.as_ref()
    }

    pub fn ssl(&self) -> bool {
        self.ssl
    }

    pub fn host(&self) -> &str {
        self.host.as_deref().unwrap_or("localhost")
    }

    pub fn port(&self) -> u16 {
        self.port.unwrap_or(6379)
    }

    pub fn username(&self) -> &str {
        self.username.as_deref().unwrap_or("")
    }

    pub fn password(&self) -> &str {
        self.password.as_deref().unwrap_or("")
    }

    pub fn database(&self) -> u16 {
        self.database.unwrap_or(0)
    }

    pub fn max_size(&self) -> u32 {
        self.max_size.unwrap_or(10)
    }

    pub fn min_idle(&self) -> u32 {
        self.min_idle.unwrap_or(0)
    }

    pub fn connect_timeout(&self) -> u16 {
        self.connect_timeout.unwrap_or(30)
    }

    pub fn idle_timeout(&self) -> u16 {
        self.idle_timeout.unwrap_or(600)
    }

}